package org.gc.amino.universe;

public class Rectangle {
	private double max_x, min_x;
	private double max_y, min_y;
	
	public Rectangle(double min_x, double max_x, double min_y, double max_y) {
		this.max_x = max_x;
		this.min_x = min_x;
		this.max_y = max_y;
		this.min_y = min_y;
	}
	
	public Rectangle(Rectangle rect) {
		this.max_x = rect.max_x;
		this.min_x = rect.min_x;
		this.max_y = rect.max_y;
		this.min_y = rect.min_y;
	}

	public double getMaxX() {
		return max_x;
	}

	public double getMinX() {
		return min_x;
	}
	
	public double getMidX() {
		return (min_x + max_x) / 2;
	}

	public double getMaxY() {
		return max_y;
	}

	public double getMinY() {
		return min_y;
	}
	
	public double getMidY() {
		return (max_y + min_y) / 2;
	}
	
	/**
	 * Returns a new rectangle that is a quadrant of 'this'.
	 * @param index An integer between 0 and 3
	 *        <li>0 : top    left</li>
	 *        <li>1 : bottom left</li>
	 *        <li>2 : top    right</li>
	 *        <li>3 : bottom right</li>
	 * @return The corresponding quadrant
	 */
	public Rectangle getQuadrant(int index) {
		double min_x = this.min_x, max_x = this.getMidX();
		double min_y = this.min_y, max_y = this.getMidY();
		
		// if index is either 2 or 3, the quadrant is on the right (higher x values)
		// <=> if(index / 2 == 1)
		if((index >> 1) == 1) {
			min_x = this.getMidX();
			max_x = this.max_x;
		}
		
		// if index is either 1 or 3, the quadrant is on the bottom (higher y values)
		// <=> if(index % 2 == 1)
		if((index & 1) == 1) {
			min_y = this.getMidY();
			max_y = this.max_y;
		}
		
		return new Rectangle(min_x, max_x, min_y, max_y);
	}
	
	public boolean intersects(Rectangle rect) {
		boolean x_intersection = !(rect.max_x < this.min_x || rect.min_x > this.max_x);
		boolean y_intersection = !(rect.max_y < this.min_y || rect.min_y > this.max_y);
		return x_intersection && y_intersection;
	}
	
	public String toString() {
		return "[ " + this.min_x + ":" + this.max_x + ", " + this.min_y + ":" + this.max_y + "]";
	}
}
